package com.weibo4terios.logic;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import com.weibo.net.AccessToken;
import com.weibo.net.DialogError;
import com.weibo.net.Utility;
import com.weibo.net.Weibo;
import com.weibo.net.WeiboDialogListener;
import com.weibo.net.WeiboException;
import com.weibo4terios.conts.CommonStrs;
import com.weibo4terios.ui.LoginActivity;
import com.weibo4terios.util.SaveParam;

/**  
 * OAuth2Activity.java
 * 2012-10-29 下午6:07:59
 * @author Wang Tengrui  
 */
public class OAuth2Activity extends Activity {
	private Weibo mWeibo;

	@SuppressWarnings("static-access")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		requestWindowFeature(getWindow().FEATURE_NO_TITLE);// 取消标题显示
		super.onCreate(savedInstanceState);
		mWeibo = Weibo.getInstance();
		mWeibo.setupConsumerConfig(CommonStrs.CONSUMER_KEY,
				CommonStrs.CONSUMER_SECRET);
		mWeibo.setRedirectUrl(CommonStrs.mRedirectUrl);
		mWeibo.authorize(OAuth2Activity.this, new AuthDialogListener());
	}
	
	@Override
	protected void onDestroy() {
		Utility.clearCookies(this);
		super.onDestroy();
	}
	
	class AuthDialogListener implements WeiboDialogListener {

		/**
		 * 授权完成之后保存授权用户信息
		 */
		@Override
		public void onComplete(Bundle values) {
			String token = values.getString("access_token");
			String expires_in = values.getString("expires_in");

			String expires_date = String.valueOf(System.currentTimeMillis()
					+ Long.parseLong(expires_in) * 1000);// 把expires_in换算成过期时间存入expires_date
			values.putString("expires_date", expires_date);// 添加过期时间

			AccessToken accessToken = new AccessToken(token,
					CommonStrs.CONSUMER_SECRET);

			accessToken.setExpiresIn(expires_in);
			Weibo.getInstance().setAccessToken(accessToken);
			SaveParam.saveNowUser(OAuth2Activity.this, values);// 把当前用户保存到SharedPreferences

			startActivity(new Intent(OAuth2Activity.this, LoginActivity.class));
		}

		@Override
		public void onWeiboException(WeiboException e) {
			Toast.makeText(getApplicationContext(), "授权异常 : " + e.getMessage(),
					Toast.LENGTH_LONG).show();
		}

		@Override
		public void onError(DialogError e) {
			Toast.makeText(getApplicationContext(), "授权失败 : " + e.getMessage(),
					Toast.LENGTH_LONG).show();
		}

		@Override
		public void onCancel() {
			Toast.makeText(getApplicationContext(), "取消授权", Toast.LENGTH_LONG)
					.show();
		}

	}

}
